package com.zdc.learn.netty.heart;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class HeartNettyServer {

    public static void main(String[] args) throws Exception {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);

        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap bootstrap = new ServerBootstrap();

            ServerBootstrap channel = bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    //可连接的连接数 队列（对应tcp/ip 协议）
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //childHandler 处理客户端连接之后的请求
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //获取pipeline
                            ChannelPipeline pipeline = socketChannel.pipeline();

                            /**
                             * 1、加入一个idleStateHandler 心跳机制
                             * 说明：
                             * 1、IdleStateHandler 是netty 提供的处理空闲状态的处理器
                             * 2、long readerIdleTime :表示多长时间没有读，就会发送一个心跳检测包检测是否连接
                             * 3、long writerIdleTime : 表示多长时间没有写，就会发送一个心跳检测包检测是否连接
                             * 4、long allIdleTIme :表示多长时间没有读写，就会发送一个心跳检测包检测是否连接
                             */
                            pipeline.addLast(new IdleStateHandler(2,5,7, TimeUnit.SECONDS));
                            //业务处理器
                            pipeline.addLast(new HeartServerChatHandler());
                        }
                    });
            System.out.println("服务启动.....................");
            ChannelFuture future = channel.bind(6666).sync();
            //监听关闭
            future.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }


    }
}
